/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Entity.Dosen;
import Entity.DosenPemilikKarya;
import Entity.PublikasiKaryaDosen;
import Entity.User;
import Model.DaftarPemilikKarya;
import Model.DaftarPublikasiKaryaDosen;
import Model.DosenModel;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author user
 */
public class TambahKaryaIlmiah extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        HttpSession session = request.getSession();

        ArrayList ListRole = new ArrayList();
        ListRole = (ArrayList) session.getAttribute("role");

        boolean bukanRole = true;
        if (session.getAttribute("role") != null) {
            for (int i = 0; i < ListRole.size(); i++) {
                if (ListRole.get(i).equals("dosen")) {
                    bukanRole = false;
                }
            }
        }

        if (session.getAttribute("role") == null) {
            Login servlet = new Login();
            servlet.processRequest(request, response);
        } else if (bukanRole) {
            request.setAttribute("menu", "home");
            request.setAttribute("submenu", "");
            RequestDispatcher dis = request.getRequestDispatcher("AccessDenied.jsp");
            dis.forward(request, response);
        } else {

            PublikasiKaryaDosen pubKarya = new PublikasiKaryaDosen();
            DaftarPublikasiKaryaDosen daftarPubKarya = new DaftarPublikasiKaryaDosen();

            String status = "";
            if (request.getParameter("status") != null) {
                status = request.getParameter("status");
            }

            if (status.equals("submit")) {
                String[] array = new String[6];

                Calendar c = Calendar.getInstance();
                c.setTime(new Date());
                int Month = c.get(Calendar.MONTH) + 1;
                String tanggal = c.get(Calendar.DATE) + "" + Month + "" + c.get(Calendar.YEAR) + "_" + c.get(Calendar.HOUR_OF_DAY) + "" + c.get(Calendar.MINUTE);

                try {

                    PrintWriter out = response.getWriter();

                    // Check that we have a file upload request

                    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

                    // Create a factory for disk-based file items  
                    DiskFileItemFactory factory = new DiskFileItemFactory();

                    // Create a new file upload handler  
                    ServletFileUpload fileUpload = new ServletFileUpload(factory);

                    // Parse the request 
                    List items = fileUpload.parseRequest(request);
                    Iterator ir = items.iterator();
                    int count = 0;
                    while (ir.hasNext()) {
                        FileItem item = (FileItem) ir.next();
                        if (item.isFormField()) {
                            //mengambil data input yang selain file
                            out.print(item.getFieldName());
                            array[count] = item.getString();
                            count++;
                        } else {
                            //String d = + "-"+c.MONTH+"-"+c.DATE;

                            String nama = tanggal + "_" + item.getName();
                            String location = "C:" + File.separator + "File" + File.separator + "KaryaIlmiah";
                            String uploadFile = location + File.separator + nama;
                            File file = new File(uploadFile);
                            item.write(file);

                            pubKarya.setFileKarya(nama);
                            pubKarya.setTanggalUploadFile(c.get(Calendar.YEAR) + "" + Month + "" + c.get(Calendar.DATE));
                            pubKarya.setTipeFileKarya(item.getContentType());
                            pubKarya.setUkuranFileKarya("" + item.getSize() + " KB");
//                          
                            System.out.println(nama);
                            System.out.println(item.getSize());
                            System.out.println(item.getContentType());

                        }
                    }
                } catch (FileUploadException ex) {
                    log("Error encountered while parsing the request", ex);
                } catch (Exception ex) {
                    log("Error encountered while uploading file", ex);
                }

                DosenPemilikKarya dosenPengupload = new DosenPemilikKarya();

                User user = new User();
                String idUser = null;

                pubKarya.setJudulKarya(array[0]);

                int jmlDosenIn = 0, jmlDosenEks = 0;

                pubKarya.setTempatPublikasi(array[1]);
                pubKarya.setTahunPubKarya(array[2]);
                pubKarya.setIdTingkatPublikasi(Integer.parseInt(array[3]));
                jmlDosenIn = Integer.parseInt(array[4]);
                jmlDosenEks = Integer.parseInt(array[5]);
                idUser = (String) session.getAttribute("id_user");
                user.setIdUser(idUser);
                
                pubKarya.setUniqueKey(tanggal + Math.random());
                pubKarya.setUserPengupload(user);

                Dosen dosen = new Dosen();
                dosen.setUser(user);

                dosenPengupload.setStatusPengupload("1");
                dosenPengupload.setPublikasiKarya(pubKarya);
                dosenPengupload.setDosen(dosen);
                session.setAttribute("dosenPengupload", dosenPengupload);

                session.setAttribute("pubKarya", pubKarya);
                session.setAttribute("jmlDosenIn", jmlDosenIn);
                session.setAttribute("jmlDosenEks", jmlDosenEks);

                DosenModel dosenModel = new DosenModel();
                List<Dosen> listDosen = new ArrayList<Dosen>();
                listDosen = dosenModel.DaftarDosen();

                request.setAttribute("dosen", listDosen);
                request.setAttribute("menu", "ppm");
                request.setAttribute("submenu", "karyaIlmiah");

                RequestDispatcher dis = request.getRequestDispatcher("ppm/halamanPemilikKarya.jsp");
                dis.forward(request, response);

            } else if (status.equals("submitAnggota")) {

                int jumlahDosen = Integer.parseInt((String) "" + session.getAttribute("jmlDosenIn"));
                int jmlDosenEks = Integer.parseInt((String) "" + session.getAttribute("jmlDosenEks"));

                pubKarya = (PublikasiKaryaDosen) session.getAttribute("pubKarya");

                boolean sukses = daftarPubKarya.tambahPublikasiPublikasiKaryaDosen(pubKarya);
                String pesan = null;
                String isiPesan = null;
                if (sukses) {
                    pubKarya = daftarPubKarya.detailPublikasiKaryaDosen(pubKarya);
                    DaftarPemilikKarya ModelDosenPemilikKarya = new DaftarPemilikKarya();
                    DosenPemilikKarya dosenPengupload = (DosenPemilikKarya) session.getAttribute("dosenPengupload");

                    for (int i = 0; i < ListRole.size(); i++) {
                        if (ListRole.get(i).equals("dosen")) {
                            dosenPengupload.setPublikasiKarya(pubKarya);
                            ModelDosenPemilikKarya.tambahTimDosenKaryaIlmiah(dosenPengupload);
                        }
                    }

                    for (int i = 1; i <= jumlahDosen; i++) {
                        String idDosen = request.getParameter("dosen[" + i + "]");
                        System.out.println("HEHEHE" + idDosen);
                        User user = new User();
                        user.setIdUser(idDosen);

                        Dosen dosen = new Dosen();
                        dosen.setUser(user);

                        dosenPengupload.setStatusPengupload("0");
                        dosenPengupload.setPublikasiKarya(pubKarya);
                        dosenPengupload.setDosen(dosen);

                        ModelDosenPemilikKarya.tambahTimDosenKaryaIlmiah(dosenPengupload);
                    }

                    for (int i = 1; i <= jmlDosenEks; i++) {
                        String namaPemilik = request.getParameter("pemilikEks[" + i + "]");
                        System.out.println("HEHEHE" + namaPemilik);

                        dosenPengupload.setStatusPengupload("0");
                        dosenPengupload.setPublikasiKarya(pubKarya);
                        dosenPengupload.setNamaPeneliti(namaPemilik);

                        ModelDosenPemilikKarya.tambahTimDosenKaryaIlmiah(dosenPengupload);
                    }

                    pesan = "sukses";
                    isiPesan = "Data publikasi karya ilmiah berhasil ditambahkan";

                } else {
                    pesan = "gagal";
                    isiPesan = "Data publikasi karya ilmiah tidak berhasil ditambahkan";
                }
//                session.setAttribute("pesan", pesan);
//                session.setAttribute("isiPesan", isiPesan);

                request.setAttribute("pesan", pesan);
                request.setAttribute("isiPesan", isiPesan);
                TampilDaftarKaryaIlmiah servlet = new TampilDaftarKaryaIlmiah();
                servlet.processRequest(request, response);

            } else if(status.equals("batal")){
                TampilDaftarKaryaIlmiah servlet = new TampilDaftarKaryaIlmiah();
                servlet.processRequest(request, response);
            }else {

                Calendar d = Calendar.getInstance();
                d.setTime(new Date());
                //String d = + "-"+c.MONTH+"-"+c.DATE;
                int tahun = d.get(Calendar.YEAR);
                int listTahun[] = new int[10];
                for (int i = 0; i < 10; i++) {
                    listTahun[i] = tahun;
                    tahun--;
                }
                
                request.setAttribute("tahun", listTahun);
                request.setAttribute("menu", "ppm");
                request.setAttribute("submenu", "karyaIlmiah");

                RequestDispatcher dis = request.getRequestDispatcher("ppm/halamanTambahPubKarya.jsp");
                dis.forward(request, response);
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
